package  tpcar.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import tpcar.ejb.CarteDeVisite;
import tpcar.ejb.ConsultPersonne;
import tpcar.ejb.Consultator;
import tpcar.ejb.Personne;

public class ConsultServlet extends HttpServlet {
	private static final long serialVersionUID = -1322434790655798901L;

// this tag not work, i have to figure out why 
//@EJB(beanName="java:comp/env/consultatorbean")
 private Consultator consult;

  /**
     * Lookup the stateless bean and gets a reference on it.
     * @return the stateless bean business interface.
     * @throws Exception if the bean cannot be retrieved.
     */
    private Consultator getBean() throws Exception {
        
        Context initialContext = new InitialContext();

        Object o = initialContext.lookup("consultatorbean");
      
        if (o instanceof Consultator) {
            return (Consultator) o;
        }
        else throw new Exception("Cannot cast object into Consultator");
       
    }
    
private ConsultPersonne getPersonBean() throws Exception {
        
        Context initialContext = new InitialContext();

        Object o = initialContext.lookup("ConsultPersonneBean");
      
        if (o instanceof ConsultPersonne) {
            return (ConsultPersonne) o;
        }
        else throw new Exception("Cannot cast object into ConsultPerson");
       
    }
    
	/**
     * React to a GET request coming from the client. 
     * Exec the request, print the result.
     * @throws Exception if the bean cannot be retrieved.
     */
	protected void doGet ( HttpServletRequest req , HttpServletResponse res)
	throws ServletException , IOException {
		

		res.setContentType("text/html");
		PrintWriter out = res.getWriter();
        boolean card=false;        
		
        if(req.getParameter("searchCard")!=null)
        	card=true;
        else if(req.getParameter("searchallCard")!=null)
        	card= true;
        else if(req.getParameter("searchPerson")!=null)
        	card=false;
        else if(req.getParameter("searchallPerson")!=null)
        	card=false;
                	
		head(out);
		lookPerson(out);
		lookCard(out);
		
		if(card)
			look(req.getParameter("prefix"), out, req.getParameter("searchallCard")!=null);
		else
		lookPerson(req.getParameter("prefix"), out, req.getParameter("searchallPerson")!=null);
		
                foot(out);
	}
	
		/**
     * Find a card with a given prefix or list all all existing card.
     */
	private void look(String prefix, PrintWriter out, boolean all) {

//		Doing the search ...
    List<CarteDeVisite> result = null ;
		try {
			Consultator consult = getBean();
			if (all){
				result = consult.listerTous();
				out.println("<h2> Current List  </h2>");
				printResult(result , out );
		  } else if (prefix != null && prefix.length()!=0){
		  		result = consult.rechercherPrefix( prefix );
					out.println("<h2> Search Result for " + prefix + " </h2>");
					printResult(result , out );
		  }
			
		} catch ( Exception e) {
			out.println("<h3> Unable to invoke the Consultator !</h3>");
			out.println(e + "<br/>");
			return ;
		}
	}

	
	/**
     * Find a card with a given prefix or list all all existing card.
     */
	private void lookPerson(String prefix, PrintWriter out, boolean all) {

//		Doing the search ...
    List<Personne> result = null ;
		try {
			ConsultPersonne consult = getPersonBean();
			if (all){
				result = consult.listerTous();
				out.println("<h2> Current List  </h2>");
				printPersonneResult(result , out );
		  } else if (prefix != null && prefix.length()!=0){
		  		result = consult.rechercherPrefix( prefix );
					out.println("<h2> Search Result for " + prefix + " </h2>");
					printPersonneResult(result , out );
		  }
			
		} catch ( Exception e) {
			out.println("<h3> Unable to invoke the ConsultPerson!</h3>");
			out.println(e + "<br/>");
			e.printStackTrace(out);
			return ;
		}
	}
	
	
/**
    * print the admin gui
    */
	private void printResult(List<CarteDeVisite> cartes, PrintWriter out ) throws Exception {
		if (cartes == null|| cartes.isEmpty()) {
			out. println ("<strong> No match found ! </strong>");
		}else {
			for (CarteDeVisite carte : cartes) {
				out.println("<h4>" + carte.getNom () + " " + carte.getPrenom() + "</h4>");
				out.println("<ul>");
				out.println("<li>Telephone : "+ carte.getPhone() +"</li>");
				out.println("<li>Email: "+ carte.getEmail() +"</li>");
				out.println("</ul>");
			}
		}
	}


	/**
	    * print the admin gui
	    */
		private void printPersonneResult(List<Personne> personnes, PrintWriter out ) throws Exception {
			if (personnes == null|| personnes.isEmpty()) {
				out. println ("<strong> No match found ! </strong>");
			}else {
				for (Personne personne : personnes) {
					out.println("<h4>" + personne.getNom () + " " + personne.getPrenom() + "</h4>");
					out.println("<ul>");
					out.println("<li>Place of Birth: "+ personne.getLieuNaissance() +"</li>");
					out.println("<li>Date of Birth: "+ personne.getDateNaissance() +"</li>");
					out.println("<li>Gender: "+ personne.getSexe() +"</li>");
					out.println("</ul>");
				}
			}
		}	
	
	
	/**
    * print the admin gui
    */
	private void head(PrintWriter out) {
		out.println("<html><head><title>User interface</title></head>");
		out.println("<body>");
	}
	
	
	private void lookCard(PrintWriter out)
	{
		out.println("<h1>Looking for a card ?</h1><br>");
		out.println("<form method =\"get\">");
		out.println("<p>");
		out.println(" Name:&nbsp;" + "<input type=\"text\" name=\"prefix\"/>");
		out.println("<br/><input type=\"submit\" name=\"searchCard\" value =\"Search !\"/>");
		out.println("<br/><input type=\"submit\" name=\"searchallCard\" value =\"Search All !\"/>");
		out.println("</p>");
		out.println("</form >");
	}
	
	private void lookPerson(PrintWriter out)
	{
		out.println("<h1>Looking for someone ?</h1><br>");
		out.println("<form method =\"get\">");
		out.println("<p>");
		out.println(" Name:&nbsp;" + "<input type=\"text\" name=\"prefix\"/>");
		out.println("<br/><input type=\"submit\" name=\"searchPerson\" value =\"Search !\"/>");
		out.println("<br/><input type=\"submit\" name=\"searchallPerson\" value =\"Search All !\"/>");
		out.println("</p>");
		out.println("</form >");
	}
	
	/*
        private void add(PrintWriter out)
        {
            out.println("<h1> Add/Modify/Delete someone</h1>");
            out.println("<form method =\"get\">");
            out.println(" Name:&nbsp;" + "<input type=\"hidden\" name=\"prefix\" value=\"test\"/>");
            out.println("<br/><input type=\"submit\" name=\"Add\" value =\"Add !\"/>");
            out.println("<br/><input type=\"submit\" name=\"Modify\" value =\"Modify !\"/>");
            out.println("<br/><input type=\"submit\" name=\"Delete\" value =\"Delete !\"/>");
            out.println("</form >");
        }
       */ 
        
	/**
    * print the admin gui
    */
	private void foot( PrintWriter out ) {
		out.println("</body >");
		out.println("</html >");
		out.close();
	}
}
